package controllers

import (
	"os"
	"path"
	"quickstart/models"
	"time"

	"github.com/astaxie/beego"
)

type UserControllers struct {
	beego.Controller
}

// type JSONStruct struct {
//     Code int  `json:"code"`
//     Msg  string  `json:"msg"`
// 	List []string `json:"list"`
// }

//模板输出用户列表
func (c *UserControllers) Get() {
	user := models.GetUserList()
	//以json输出数据
	c.Data["user"] = &user
	c.TplName = "user_list.html"
}

//获取用户列表
func (c *UserControllers) UserList() {
	//获取所有用户
	user := models.GetUserList()
	//以json输出数据
	c.Data["json"] = models.GeneralResp{Code: 1, Data: user}
	c.ServeJSON()
}

//获取单个用户数据
func (c *UserControllers) UserById() {
	id, _ := c.GetInt("id")

	//获取单用户数据
	user := models.GetUserById(id)

	c.Data["json"] = models.GeneralResp{Code: 1, Data: user}
	c.ServeJSON()
}

//新增用户
func (c *UserControllers) AddUser() {
	username := c.GetString("username")
	password := c.GetString("password")
	add := models.AddUserData(username, password)
	c.Data["json"] = &add
	c.ServeJSON()
}

//修改用户资料
func (c *UserControllers) SetUser() {
	id, _ := c.GetInt("id")
	username := c.GetString("username")
	password := c.GetString("password")
	err := models.UpdateUser(username, password, id)
	c.Data["err"] = err
	c.ServeJSON()
}

//删除用户
func (c *UserControllers) DelUser() {
	id, _ := c.GetInt("id")
	err := models.DelUserById(id)
	if err != 1 {
		c.Data["json"] = models.GeneralResp{Code: 0, Error: "删除失败"}
	} else {
		c.Data["json"] = models.GeneralResp{Code: 1, Error: "删除成功"}
	}
	// c.Data["err"] = err
	c.ServeJSON()
}

type Sizer interface {
	Size() int64
}

//图片上传
func (this *UserControllers) UploadFiles() {
	f, h, err := this.GetFile("file") //获取上传的文件this.GetFile("file")
	if err != nil {
		this.Data["json"] = models.GeneralResp{Code: 0, Error: "get file fail!"}
		this.ServeJSON()
		return
	}
	defer f.Close() //关闭上传的文件，不然的话会出现临时文件不能清除的情况
	ext := path.Ext(h.Filename)
	//验证后缀名是否符合要求
	var AllowExtMap map[string]bool = map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".gif":  true,
		".csv":  true,
		".docx": true,
		".xlsx": true,
		".xls":  true,
		".doc":  true,
		".pdf":  true,
		".txt":  true,
		".html": true,
		".ppt":  true,
		".pptx": true,
	}
	var Filebytes = 1 << 24 //文件小于16兆
	if _, ok := AllowExtMap[ext]; !ok {
		this.Data["json"] = models.GeneralResp{Code: 0, Error: "not allowed file format!"}
		this.ServeJSON()
		return
	}

	if fileSizer, ok := f.(Sizer); ok {
		fileSize := fileSizer.Size()
		if fileSize > int64(Filebytes) {
			this.Data["json"] = models.GeneralResp{Code: 0, Error: "upload file error: file size exceeds 16M!"}
			this.ServeJSON()
		} else {
			uploadDir := "static/upload/" + time.Now().Format("2006/01/02/")
			err = os.MkdirAll(uploadDir, os.ModePerm)
			if err != nil {
				this.Data["json"] = models.GeneralResp{Code: 0, Error: "create upload dir fail:" + err.Error()}
				this.ServeJSON()
				return
			}
			fpath := uploadDir + h.Filename
			err = this.SaveToFile("file", fpath)
			if err != nil {
				this.Data["json"] = models.GeneralResp{Code: 0, Error: err.Error()}
				this.ServeJSON()
				//this.Ctx.WriteString(fmt.Sprintf("%v", err))
			}
			this.Data["json"] = models.GeneralResp{Code: 1, Data: fpath}
			this.ServeJSON()
		}
	} else {
		this.Data["json"] = models.GeneralResp{Code: 0, Error: "unable to read file size!"}
		this.ServeJSON()
	}

}
